package 字符串算法;

import java.util.Arrays;

public class 最长公共前缀 {

    private static boolean chechStrs(String[] strs){
        boolean flag = false;
        if (strs != null){
            for (int i = 0; i < strs.length; i++) {
                if (strs[i] != null && strs[i].length() != 0){
                    flag = true;

                }else {
                    flag = false;
                    break;
                }
            }
        }
           return flag;
    }


    public static String replaceSpace(String[] strs){
        //检查是否合格，不合格直接返回空串
       if (!chechStrs(strs)){
           return "";
       }
       //数组长度
        int length = strs.length;
        StringBuffer res = new StringBuffer();
        Arrays.sort(strs);
        int m = strs[0].length();
        int n = strs[length - 1].length();
        int min = Math.min(m, n);
        for (int i = 0; i < min; i++) {
        if (strs[0].charAt(i) == strs[length-1].charAt(i)){
            res.append(strs[0].charAt(i));
        }else{
            break;
        }

        }
        return res.toString();

    }

    public static void main(String[] args) {
        String[] strs = { "customer", "car", "cat" };
        System.out.println(replaceSpace(strs));
    }
}
